//
//  htvsampleinfo.m
//  PHApp
//
//  Created by zhangwq on 16/4/8.
//  Copyright © 2016年 HT. All rights reserved.
//

#import "htvsampleinfo.h"
#import <AVFoundation/AVFoundation.h>
#import "HTFrameKit.h"
#import "HTSysKit.h"
#import "HTFrameConvert.h"
#import "UIImageView+WebCache.h"
#import <AudioToolbox/AudioToolbox.h> //声音提示

#define SOUNDID  1004


@interface htvsampleinfo ()<AVCaptureMetadataOutputObjectsDelegate>//用于处理采集信息的代理
{
    AVCaptureSession * session;//输入输出的中间桥梁
    CGFloat buttomHeight;
    UIView *backview;
    UIView *uv;
    CGFloat width;
    CGFloat height;
    
    NSMutableArray *itemArray;
    
    NSString *smtext;
    UIColor *backcolor;
    UIView *sampleview;
    
    NSTimer *timer;
    UIView *line;
    CGFloat lineH;
    
    
}

@property (nonatomic, strong) NSOperationQueue *queue;

@end

@implementation htvsampleinfo

- (NSOperationQueue *)queue {
    if (!_queue) _queue = [[NSOperationQueue alloc] init];
    return _queue;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.separatorStyle=NO;
    
    CGRect rect = [[UIScreen mainScreen] bounds];
    CGSize size = rect.size;
    width = size.width;
    height = size.height;
    
    buttomHeight=0;
    
    itemArray=[NSMutableArray array];
    
    backcolor=[UIColor colorWithRed:150.0/255.0 green:150.0/255.0 blue:150.0/255.0 alpha:1.0];
    
    smtext=@"";
    
    
    sampleview=[[UIView alloc]initWithFrame:CGRectMake(0, height, width, 40)];
    sampleview.backgroundColor=[UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0];
    sampleview.layer.borderWidth=0.6;
    sampleview.layer.borderColor=[UIColor colorWithRed:225.0/255.0 green:225.0/255.0 blue:225.0/255.0 alpha:1.0].CGColor;

    [self.view addSubview:sampleview];
    
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(width/2-18,2, 36, 36)];
    [btn setImage:[UIImage imageNamed:@"sm2"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(smAction:) forControlEvents:UIControlEventTouchUpInside];
    [sampleview addSubview:btn];
    
    lineH=height/2-140;
    
    
    [self setsm];
    
}


-(void)setsm{
    self.tableView.scrollEnabled=NO;
    
    timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    
    self.tableView.contentOffset=CGPointMake(0, -64);
    
    backview=[[UIView alloc]initWithFrame:CGRectMake(0, buttomHeight+64, width, height)];
    backview.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:backview];
    
    UIImageView *photo=[[UIImageView alloc]initWithFrame:CGRectMake(width/2-100, height/2-140, 200, 200)];
    photo.image=[UIImage imageNamed:@"sm"];
    [photo setClipsToBounds:YES];
    [photo setContentMode:UIViewContentModeScaleAspectFill];
    photo.layer.masksToBounds=YES;
    photo.userInteractionEnabled=YES;
    photo.layer.cornerRadius=4;
    [backview addSubview:photo];
    
    
    line=[[UIView alloc]initWithFrame:CGRectMake(width/2-100, height/2-40, 200, 1)];
    line.backgroundColor=[UIColor redColor];
    [backview addSubview:line];
    
    
    UILabel *lb=[[UILabel alloc]initWithFrame:CGRectMake(0, height/2+70, width, 20)];
    lb.text=@"将二维码/条码放入框内，即可扫描";
    lb.textColor=[UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0];
    lb.font=[UIFont fontWithName:@"Arial" size:12.0];
    lb.textAlignment=UITextAlignmentCenter;
    [backview addSubview:lb];
    
    
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(width/2-100, height/2+100, 200, 30)];
    [btn setTitle:@"扫描结束" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    btn.font=[UIFont fontWithName:@"Arial" size:12.0];
    [btn addTarget:self action:@selector(jsAction:) forControlEvents:UIControlEventTouchUpInside];
    [backview addSubview:btn];
    
    
    
    
    //获取摄像设备
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    //创建输出流
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
    //设置代理 在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //初始化链接对象
    session = [[AVCaptureSession alloc]init];
    //高质量采集率
    [session setSessionPreset:AVCaptureSessionPresetHigh];
    
    [session addInput:input];
    [session addOutput:output];
    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
    layer.frame=self.view.layer.bounds;
    [backview.layer insertSublayer:layer atIndex:0];
    //开始捕获
    [session startRunning];
}

-(void)timerAction:(id)sender{
    
    line.frame=CGRectMake(width/2-100, lineH, 200, 1);
    lineH+=1;
    if(lineH>width/2+140){
        lineH=width/2;
    }
}


-(void)jsAction:(UIButton*)sender{
    
    [backview removeFromSuperview];
    self.tableView.scrollEnabled=YES;
    [timer invalidate];
    
}

-(void)smAction:(UIButton*)sender{
    
    [self setsm];
}



-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count>0) {
        [session stopRunning];
        //一句话解决iphone  ipad 声音提示
        AudioServicesPlaySystemSound(SOUNDID);
        
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        //输出扫描字符串
        NSLog(@"扫描信息：%@",metadataObject.stringValue);
        [backview removeFromSuperview];
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              metadataObject.stringValue,@"itemCode",
                              @"印花白蛋", @"itemName",
                              @"120D*70D单面提花", @"itemStd",
                              @"花色很漂亮", @"describe",
                              @"http://7xshdz.com2.z0.glb.clouddn.com/39b1OOOPICa9.jpg", @"picPath",                         nil];
        
        [itemArray insertObject:dict atIndex:0];
        [self.tableView reloadData];
        self.tableView.scrollEnabled=YES;
        [timer invalidate];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section==0){
        return [itemArray count];
    }
    else{
        return 1;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if([indexPath section]==0){
        return 100.0;
    }
    else{
        return 40.0;
    }
}



- ( UITableViewCell *)tableView:( UITableView *)tableView cellForRowAtIndexPath:( NSIndexPath *)indexPath{
    
    NSString *cellId = @"cellname" ;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier :cellId];
    if (cell == nil ) {
        cell = [[ UITableViewCell alloc ] initWithStyle : UITableViewCellStyleDefault reuseIdentifier :cellId] ;
    }
    
    uv=[[UIView alloc]initWithFrame:CGRectMake(0, 0, width, 30)];
    
    NSDictionary *dict=[NSDictionary dictionary];
    
    if([indexPath section]==0){
        uv=[[UIView alloc]initWithFrame:CGRectMake(0, 0, width, 100)];
        dict=[itemArray objectAtIndex:[indexPath row]];
        
        UIImageView *iv=[[UIImageView alloc]initWithFrame:CGRectMake(30,10, 80,80)];
        iv.accessibilityLabel=[dict objectForKey:@"picPath"];
        [iv setClipsToBounds:YES];
        [iv setContentMode:UIViewContentModeScaleAspectFill];
        iv.layer.masksToBounds=YES;
        iv.layer.cornerRadius = 4;
        iv.userInteractionEnabled=YES;
        [self downloadImg:iv];
        [uv addSubview:iv];
        
        UILabel *lbcode=[[UILabel alloc]initWithFrame:CGRectMake(115, 10, width, 20)];
        lbcode.text=[[NSString alloc]initWithFormat:@"编码：%@",[dict objectForKey:@"itemCode"]];
        lbcode.textColor=backcolor;
        lbcode.font=[UIFont fontWithName:@"Arial" size:12.0];
        [uv addSubview:lbcode];
        
        
        UILabel *lbname=[[UILabel alloc]initWithFrame:CGRectMake(115, 30, width, 20)];
        lbname.text=[[NSString alloc]initWithFormat:@"品名：%@",[dict objectForKey:@"itemName"]];
        lbname.textColor=backcolor;
        lbname.font=[UIFont fontWithName:@"Arial" size:12.0];
        [uv addSubview:lbname];
        
        
        UILabel *lbstd=[[UILabel alloc]initWithFrame:CGRectMake(115, 50, width, 20)];
        lbstd.text=[[NSString alloc]initWithFormat:@"规格：%@",[dict objectForKey:@"itemStd"]];
        lbstd.textColor=backcolor;
        lbstd.font=[UIFont fontWithName:@"Arial" size:12.0];
        [uv addSubview:lbstd];
        
        UILabel *lbdes=[[UILabel alloc]initWithFrame:CGRectMake(115, 70, width, 20)];
        lbdes.text=[[NSString alloc]initWithFormat:@"描述：%@",[dict objectForKey:@"describe"]];
        lbdes.textColor=backcolor;
        lbdes.font=[UIFont fontWithName:@"Arial" size:12.0];
        [uv addSubview:lbdes];
        
        
        
    }
    
    if([indexPath section]==1){
        uv=[[UIView alloc]initWithFrame:CGRectMake(0, 0, width, 40)];
    }

    
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.accessoryView=uv;
    
    
    
    return cell;
}



- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if([indexPath section]==0){
        return YES;
    }
    else{
        return NO;
    }
    
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [itemArray removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
    }
}



- (IBAction)backAction:(UIButton *)sender {
     [self dismissViewControllerAnimated: YES completion: nil ];
}


- (void)downloadImg:(UIImageView *)theImageView {
    
    NSString *imageName=[[NSString alloc]initWithFormat:@"%@?imageView2/2/w/200",theImageView.accessibilityLabel];
    NSURL *imagePath = [NSURL URLWithString:imageName];
    [self.queue addOperationWithBlock: ^{
        
        //在主线程中更新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock: ^{
            
            [theImageView sd_setImageWithURL:imagePath placeholderImage:[UIImage imageNamed:@"nopic"]];
            
            
            
        }];
    }];
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint scroll=scrollView.contentOffset;
    buttomHeight=scroll.y;
    sampleview.frame=CGRectMake(0, height-40+buttomHeight, width, 40);
}
@end
